from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from django.contrib.auth.decorators import user_passes_test
from django.utils.decorators import method_decorator
from .middleware import APIStatsView

class APIStatsAPIView(APIView):
    """API统计接口"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        """获取API统计数据"""
        # 只允许管理员查看完整统计
        if not request.user.is_staff:
            return Response({'error': '权限不足'}, status=403)
        
        time_range = request.query_params.get('range', 'today')
        stats = APIStatsView.get_stats(time_range)
        
        return Response({
            'status': 'success',
            'data': stats,
            'time_range': time_range
        })


class UserAPIStatsView(APIView):
    """用户个人API统计"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        """获取当前用户的API使用统计"""
        from django.core.cache import cache
        from datetime import datetime
        
        user_id = request.user.id
        today = datetime.now().strftime('%Y-%m-%d')
        key = f'api_stats_user_daily_user_{user_id}_{today}'
        
        user_stats = cache.get(key, {
            'total_requests': 0,
            'success_requests': 0,
            'error_requests': 0,
            'avg_response_time': 0,
            'endpoints': {}
        })
        
        # 计算成功率
        success_rate = 0
        if user_stats['total_requests'] > 0:
            success_rate = round((user_stats['success_requests'] / user_stats['total_requests']) * 100, 2)
        
        # 处理端点数据
        endpoints = []
        for endpoint, info in user_stats.get('endpoints', {}).items():
            endpoints.append({
                'endpoint': endpoint,
                'count': info['count'],
                'avg_response_time': round(info['avg_response_time'], 3)
            })
        
        # 按使用次数排序
        endpoints.sort(key=lambda x: x['count'], reverse=True)
        
        return Response({
            'status': 'success',
            'data': {
                'total_requests': user_stats['total_requests'],
                'success_requests': user_stats['success_requests'],
                'error_requests': user_stats['error_requests'],
                'success_rate': success_rate,
                'avg_response_time': round(user_stats.get('avg_response_time', 0), 3),
                'endpoints': endpoints[:5]  # 返回前5个最常用的端点
            },
            'date': today
        })